#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Xml;

using octalforty.Componento.ComponentModel.Caching;
using octalforty.Componento.ComponentModel.Installation.Web;
using octalforty.Componento.Shared.SemanticModel;
using octalforty.Componento.Util;

namespace octalforty.Componento.ComponentModel.Installation
{
    [ComponentManifestProvider()]
    public class HttpRepositoryManifestProvider : IComponentManifestProvider
    {
        #region Private Fields
        private IHttpRequestFactoryService httpRequestFactory;
        private IComponentManifestProviderService componentManifestProvider;
        private ICacheManagerService cacheManager;
        private IRepositoryBrowserService repositoryBrowser;
        #endregion

        #region Public Properties
        /// <summary>
        /// Gets or sets a reference to the <see cref="IComponentManifestProviderService"/>.
        /// </summary>
        [Import()]
        public IComponentManifestProviderService ComponentManifestProvider
        {
            [DebuggerStepThrough]
            get { return componentManifestProvider; }
            [DebuggerStepThrough]
            set { componentManifestProvider = value; }
        }

        /// <summary>
        /// Gets or sets a reference to the <see cref="IHttpRequestFactoryService"/>.
        /// </summary>
        [Import()]
        public IHttpRequestFactoryService HttpRequestFactory
        {
            [DebuggerStepThrough]
            get { return httpRequestFactory; }
            [DebuggerStepThrough]
            set { httpRequestFactory = value; }
        }

        /// <summary>
        /// Gets or sets a reference to the <see cref="ICacheManagerService"/>.
        /// </summary>
        [Import()]
        public ICacheManagerService CacheManager
        {
            [DebuggerStepThrough]
            get { return cacheManager; }
            [DebuggerStepThrough]
            set { cacheManager = value; }
        }

        [Import()]
        public IRepositoryBrowserService RepositoryBrowser
        {
            [DebuggerStepThrough]
            get { return repositoryBrowser; }
            [DebuggerStepThrough]
            set { repositoryBrowser = value; }
        }
        #endregion

        #region IComponentManifestProvider Members
        /// <summary>
        /// Verifies whether current <see cref="IComponentManifestProvider"/> can retrieve manifest from <paramref name="uri"/>.
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public bool CanProvideManifestFrom(Uri uri)
        {
            return uri.Scheme == "componento+http";
        }

        /// <summary>
        /// Retrieves <see cref="ComponentManifest"/> from <paramref name="uri"/> for package <paramref name="componentName"/> with
        /// version requirement <paramref name="versionSpecification"/>.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="componentName"></param>
        /// <param name="versionSpecification"></param>
        /// <returns></returns>
        public ComponentManifest GetComponentManifest(string componentName, Uri uri, VersionSpecification versionSpecification)
        {
            //
            // Retrieving all descriptors
            Uri effectiveUri = new Uri(uri.OriginalString.Replace("componento+http", "http"));
            ComponentDescriptor[] descriptors = RepositoryBrowser.GetComponentDescriptors(effectiveUri);

            //
            // Searching for matching descriptor
            ComponentDescriptor descriptor = Array.Find<ComponentDescriptor>(descriptors,
                delegate(ComponentDescriptor cd)
                    {
                        return string.Compare(cd.Name, componentName, StringComparison.CurrentCultureIgnoreCase) == 0 &&
                            (versionSpecification == null || versionSpecification.Matches(cd.Version));
                    });

            if(descriptor == null)
                return null;

            IHttpRequest httpRequest = HttpRequestFactory.CreateHttpRequest(HttpMethod.Get, descriptor.ManifestUri);

            CacheEntryInfo cacheEntryInfo = CacheManager.GetCacheEntryInfo(descriptor.ManifestUri.ToString());
            if(cacheEntryInfo != null)
                httpRequest.IfModifiedSince = cacheEntryInfo.UpdatedOn;

            using(IHttpResponse httpResponse = httpRequest.GetResponse())
            {
                //
                // Use cached value if not modified
                if(httpResponse.StatusCode == HttpStatusCode.NotModified)
                    using(Stream responseStream = new MemoryStream(cacheEntryInfo.Content))
                    {
                        return ParseComponentManifest(responseStream);
                    } // using

                if(httpResponse.StatusCode != HttpStatusCode.OK)
                {
                    throw ExceptionUtil.ComponentManifestException(null,
                        "Cannot retrieve Component Manifest for Component '{0}' from URI '{1}': HTTP {2} {3}",
                        componentName, uri, httpResponse.StatusCode, httpResponse.StatusDescription);
                } // if

                Console.WriteLine("Downloading from {0}", effectiveUri);
                using(Stream responseStream = httpResponse.GetResponseStream())
                {
                    Console.WriteLine("Downloading {0:N1} Kb", httpResponse.ContentLength / 1024.0);

                    using(MemoryStream ms = new MemoryStream())
                    {
                        StreamUtil.Copy(responseStream, ms);

                        CacheManager.Add(descriptor.ManifestUri.ToString(), ms.ToArray());

                        ms.Position = 0;

                        return ParseComponentManifest(ms);
                    } // using
                    
                } // using
            } // using
        }
        #endregion

        private ComponentManifest ParseComponentManifest(Stream stream)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(stream);

            ComponentManifestParser componentManifestParser = new ComponentManifestParser();
            return componentManifestParser.ParseComponentManifest(xmlDocument);
        }
    }
}